package com.eastfair.imaster.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.eastfair.annotation.base.SubjectTypeEnum;
import com.eastfair.api.NoticeServiceFeign;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.cache.projectcore.BusinessCircleCacheKeyBuilder;
import com.eastfair.cache.redis.RedisOps;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.model.CacheKeyBuilder;
import com.eastfair.core.snowflake.DefaultUidGenerator;
import com.eastfair.enums.AuditStateEnum;
import com.eastfair.imaster.dao.BusinessCircleMapper;
import com.eastfair.imaster.dto.BusinessCircleDTO;
import com.eastfair.imaster.dto.CollectionDTO;
import com.eastfair.imaster.entity.BusinessCircle;
import com.eastfair.imaster.service.BusinessCircleService;
import com.eastfair.imaster.service.CollectionService;
import com.eastfair.imaster.vo.BusinessCircleVO;
import com.eastfair.notice.dto.CommentQuery;
import com.eastfair.notice.vo.CommentVO;
import com.eastfair.projectcore.api.ProjectCoreServiceFeign;
import com.eastfair.util.PuvUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 *
 * </p>
 *
 * @author liuxiaobai
 * @date 2021-08-31
 */
@Slf4j
@Service
@DS("#thread.tenant")
public class BusinessCircleServiceImpl extends SuperCacheServiceImpl<BusinessCircleMapper, BusinessCircle> implements BusinessCircleService {

    @Autowired
    private RedisOps redisOps;
    @Autowired
    private NoticeServiceFeign noticeServiceFeign;
    @Autowired
    private ProjectCoreServiceFeign projectCoreServiceFeign;
    @Autowired
    private CollectionService collectionService;

    @Override
    protected R<Boolean> handlerSave(BusinessCircle model) {
        //项目id
        model.setProjectId(ContextUtil.getProjectId());
        //雪花ID
        model.setId(DefaultUidGenerator.getUidOfProjectId(model.getProjectId()));
        return R.successDef();
    }

    @Override
    protected CacheKeyBuilder cacheKeyBuilder() {
        return new BusinessCircleCacheKeyBuilder();
    }

    /**************sharding 分库分表操作 *****************/
    @Override
    public boolean updateByIdOfShard(BusinessCircle entity) {
        UpdateWrapper<BusinessCircle> updateWrapper = new UpdateWrapper<>();
        //可将指定字段更新为null
        updateWrapper.lambda().eq(BusinessCircle::getProjectId, ContextUtil.getProjectId()).eq(BusinessCircle::getId, entity.getId());
        entity.setProjectId(null);
        //删除缓存
        delCache(entity);
        return SqlHelper.retBool(this.getBaseMapper().update(entity, updateWrapper));
    }

    @Override
    public void assembleBusinessCircleList(List<BusinessCircleVO> businessCircleVOList) {
        List<Long> ids = new ArrayList<>(businessCircleVOList.size());
        businessCircleVOList.forEach(businessCircleVO -> ids.add(businessCircleVO.getId()));
        //获取回复列表
        List<CommentVO> commentVOList = this.noticeServiceFeign.queryCommentList(CommentQuery.builder()
                .subjectType(SubjectTypeEnum.BUSINESS_CIRCLE.name())
                .subjectIds(ids)
                .shortList(Boolean.TRUE)
                .build()).getData();
        Map<Long, List<CommentVO>> commentMap = commentVOList.parallelStream().collect(Collectors.groupingBy(CommentVO::getSubjectId));
        //获取点赞数据
        Map<Long, CollectionDTO> collectionMap = this.collectionService.checkBatchWithNum(SubjectTypeEnum.BUSINESS_CIRCLE, ids);
        businessCircleVOList.parallelStream().forEach(businessCircleVO -> {
            //拼装pv uv
            PuvUtils.handlePuv(redisOps, businessCircleVO, SubjectTypeEnum.BUSINESS_CIRCLE, businessCircleVO.getId(), 0);
            //拼装回复
            businessCircleVO.setComments(commentMap.get(businessCircleVO.getId()));
            //拼装点赞数据
            CollectionDTO collectionDTO = collectionMap.get(businessCircleVO.getId());
            businessCircleVO.setIsLike(collectionDTO.getIsCollect());
            businessCircleVO.setLikeNum(collectionDTO.getNum());
        });
    }

    @Override
    public void assembleBusinessCircle(BusinessCircleVO businessCircleVO) {
        //拼装pv
        PuvUtils.handlePuv(redisOps, businessCircleVO, SubjectTypeEnum.BUSINESS_CIRCLE, businessCircleVO.getId(), 0);
        //拼装评论回复
        List<CommentVO> commentVOList = this.noticeServiceFeign.queryCommentList(CommentQuery.builder()
                .subjectType(SubjectTypeEnum.BUSINESS_CIRCLE.name())
                .subjectId(businessCircleVO.getId())
                .shortList(Boolean.FALSE)
                .build()).getData();
        businessCircleVO.setComments(commentVOList);
        //拼装点赞状态和点赞数
        CollectionDTO collectionDTO = this.collectionService.checkWithNum(SubjectTypeEnum.BUSINESS_CIRCLE, businessCircleVO.getId());
        businessCircleVO.setIsLike(collectionDTO.getIsCollect());
        businessCircleVO.setLikeNum(collectionDTO.getNum());
    }

    @Override
    public Boolean saveBusinessCircle(BusinessCircleDTO businessCircleDTO) {
        BusinessCircle businessCircle = BeanUtil.copyProperties(businessCircleDTO, BusinessCircle.class);
        businessCircle.setProjectId(ContextUtil.getProjectId());
        businessCircle.setExhibitionId(ContextUtil.getExhibitionId());
        businessCircle.setUserId(ContextUtil.getUserId());
        businessCircle.setUserType(ContextUtil.getSubjectType());
        businessCircle.setVerifyState(AuditStateEnum.PENDING.name());
        //todo 需补充问卷
        return super.save(businessCircle);
    }
}
